package com.mobile.ado.util.message;

import java.util.ArrayList;

import com.mobile.ado.util.message.Message.MESSAGE_TYPE;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.telephony.SmsManager;

public class MessageSender {

	private Context context;
	private SmsManager smsManager;

	public MessageSender(Context context) {
		this.context = context;
		smsManager = SmsManager.getDefault();
	}

	/**
	 * This function will send out message, including SMS, MMS, EMAIL.
	 * 
	 * @param message
	 * @param toAddress
	 * @return
	 */
	public boolean sendMessage(Message message, String[] toAddress) {
		if (message.getType() == MESSAGE_TYPE.SMS) {
			return sendTextMessage(message.getText(), toAddress);
		} else if (message.getType() == MESSAGE_TYPE.MMS) {
			return sendMultiMediaMessage(message, toAddress);
		} else if (message.getType() == MESSAGE_TYPE.EMAIL) {

		}
		return true;
	}

	private boolean sendMultiMediaMessage(Message message,
			String[] destinationAddress) {

		return false;
	}

	private boolean sendTextMessage(String message,
			String[] destinationAddresses) {

		int destinationSize = destinationAddresses.length;

		for (int i = 0; i < destinationSize; i++) {
			String destinationAddress = destinationAddresses[i];
			sendTextMessageToOneReceiver(message, destinationAddress);

		}

		return false;
	}

	private void sendTextMessageToOneReceiver(String message,
			String destinationAddress) {

		Uri uri = addMessageToOutBox();
		ArrayList<String> messages = smsManager.divideMessage(message);

		String outgoingServiceCenter = getOutgoingServiceCenter(0);
		ArrayList<PendingIntent> pendingSentIntents = new ArrayList<PendingIntent>();
		ArrayList<PendingIntent> pendingDeliveryIntents = new ArrayList<PendingIntent>();
		for (int i = 0; i < messages.size(); i++) {
			Intent sentIntent = new Intent(
					MessageConstants.MESSAGING_SENT_ACTION, uri);
			PendingIntent pendingIentIntent = PendingIntent.getBroadcast(
					context, 0, sentIntent, 0);
			pendingSentIntents.add(pendingIentIntent);
			Intent deliveryIntent = new Intent(
					MessageConstants.MESSAGING_STATUS_RECEIVED_ACTION, uri);
			PendingIntent pendingDeliveryIntent = PendingIntent.getBroadcast(
					context, 0, deliveryIntent, 0);
			pendingDeliveryIntents.add(pendingDeliveryIntent);
		}

		smsManager.sendMultipartTextMessage(destinationAddress,
				outgoingServiceCenter, messages, pendingSentIntents,
				pendingDeliveryIntents);
	}

	private Uri addMessageToOutBox() {
		// TODO Auto-generated method stub
		return null;
	}

	// TODO: implement it.
	String getOutgoingServiceCenter(int threadId) {
		return null;
	}
}
